package com.cedarhd.finance.msg.common;

import com.cedarhd.finance.msg.common.enums.ResultCode;
import com.cedarhd.finance.msg.common.exptions.AbstractApiException;
import com.cedarhd.finance.msg.common.exptions.SystemException;
import com.cedarhd.finance.msg.common.exptions.UserNotExistException;
import com.cedarhd.finance.msg.common.exptions.ValidateException;
import com.cedarhd.finance.msg.domain.service.ValidateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *
 * @author Evan
 * @date 18/03/05
 */

@FunctionalInterface
public interface ProcessAPI<T> {
    Logger logger = LoggerFactory.getLogger(ProcessAPI.class);

    default JsonResult process(HttpServletRequest request) {

        ValidateService validate = new ValidateService(request);

        return process(validate);
    }

    /**
     * 默认实现方法，统一处理异常
     * @param validate
     * @return
     */
    default JsonResult process(ValidateService validate) {
        JsonResult result = new JsonResult();
        try {
            result.resultCode = ResultCode.SUCC.getCode();
            result.msg = ResultCode.SUCC.getMsg();

            this.service(result, validate);
        } catch (ValidateException ex) {
            result = JsonResult.renderMsg(ResultCode.PARAM_ERROR, ex.getMessage());
            logger.error(ResultCode.PARAM_ERROR.getMsg(), ex);
        } catch (UserNotExistException ex) {
            result = JsonResult.renderMsg(ResultCode.USER_NOT_EXIST, ex.getMessage());
            logger.error(ResultCode.USER_NOT_EXIST.getMsg(), ex);
        } catch (SystemException ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
            logger.error(ResultCode.FAILED.getMsg(), ex);
        } catch (AbstractApiException ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
            logger.error(ResultCode.FAILED.getMsg(), ex);
        } catch (Exception ex) {
            result = JsonResult.renderMsg(ResultCode.FAILED, ex.getMessage());
            logger.error(ResultCode.FAILED.getMsg(), ex);
            ex.printStackTrace();
        }

        return result;
    }

    /**
     * 自定义实现的方法
     * @param result
     * @param validate
     * @throws IOException
     */
    void service(JsonResult<T> result, ValidateService validate) throws IOException;


}
